<template>
  <el-dialog
    v-model="visible"
    title="白名单管理"
    width="800px"
    destroy-on-close
    :before-close="handleClose"
  >
    <div v-loading="loading" class="whitelist-container">
      <!-- 白名单规则列表 -->
      <el-card class="whitelist-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">白名单规则列表</span>
            <div class="header-actions">
              <el-button
                type="primary"
                icon="CirclePlus"
                size="small"
                @click="handleAddRule"
              >
                新增规则
              </el-button>
              <el-button
                type="default"
                icon="Refresh"
                size="small"
                @click="fetchWhitelistRules"
              >
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          :data="ruleList"
          border
          row-key="id"
          @selection-change="handleRuleSelectionChange"
        >
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column
            prop="serialNumber"
            label="序号"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="规则名称"
            min-width="150"
          ></el-table-column>
          <el-table-column
            prop="type"
            label="类型"
            min-width="100"
            align="center"
          >
            <template #default="scope">
              {{ getRuleTypeName(scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="range"
            label="范围"
            min-width="150"
          ></el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            min-width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag
                :type="scope.row.status === 'enabled' ? 'success' : 'info'"
                size="small"
              >
                {{ scope.row.status === "enabled" ? "✅ 启用" : "❌ 禁用" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="creator"
            label="创建人"
            min-width="100"
          ></el-table-column>
          <el-table-column label="操作" min-width="120" align="center">
            <template #default="scope">
              <el-button
                type="text"
                size="small"
                @click="handleEditRule(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                type="text"
                size="small"
                class="text-danger"
                @click="handleDeleteRule(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div v-if="ruleList.length === 0" class="no-rules">
          暂无白名单规则，点击"新增规则"添加
        </div>
      </el-card>

      <!-- 新增/编辑规则 -->
      <el-card class="whitelist-card rule-form-card" v-if="showRuleForm">
        <template #header>
          <span class="card-title">{{
            isEditing ? "编辑规则" : "新增规则"
          }}</span>
        </template>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          label-width="100px"
          size="default"
        >
          <el-form-item
            label="规则名称 *"
            prop="name"
            :rules="[
              { required: true, message: '请输入规则名称', trigger: 'blur' },
            ]"
          >
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入规则名称"
              maxlength="50"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="规则类型 *"
            prop="type"
            :rules="[
              { required: true, message: '请选择规则类型', trigger: 'change' },
            ]"
          >
            <el-radio-group v-model="ruleForm.type" class="type-radio-group">
              <el-radio label="ip" class="type-radio">IP地址</el-radio>
              <el-radio label="ip_range" class="type-radio">IP段</el-radio>
              <el-radio label="port" class="type-radio">端口</el-radio>
              <el-radio label="cve" class="type-radio">CVE编号</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="匹配条件 *"
            prop="range"
            :rules="[
              { required: true, message: '请输入匹配条件', trigger: 'blur' },
            ]"
          >
            <template v-if="ruleForm.type === 'ip'">
              <el-input
                v-model="ruleForm.range"
                placeholder="请输入IP地址，如：10.0.1.100"
              ></el-input>
            </template>

            <template v-if="ruleForm.type === 'ip_range'">
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-input
                    v-model="ipRange.startIp"
                    placeholder="起始IP"
                  ></el-input>
                </el-col>
                <el-col :span="12">
                  <el-input
                    v-model="ipRange.endIp"
                    placeholder="结束IP"
                  ></el-input>
                </el-col>
                <el-col :span="24" style="margin-top: 10px">
                  <div class="or-text">或</div>
                  <el-input
                    v-model="ipRange.cidr"
                    placeholder="CIDR格式，如：10.0.1.0/24"
                  ></el-input>
                </el-col>
              </el-row>
            </template>

            <template v-if="ruleForm.type === 'port'">
              <el-input
                v-model="ruleForm.range"
                placeholder="请输入端口，多个用逗号分隔，如：8080,8888"
              ></el-input>
            </template>

            <template v-if="ruleForm.type === 'cve'">
              <el-input
                v-model="ruleForm.range"
                placeholder="请输入CVE编号，多个用逗号分隔，如：CVE-2023-12345,CVE-2023-67890"
              ></el-input>
            </template>
          </el-form-item>

          <el-form-item label="适用维度">
            <el-checkbox-group v-model="ruleForm.dimensions">
              <el-checkbox label="vulnerability" class="dimension-checkbox"
                >漏洞风险</el-checkbox
              >
              <el-checkbox label="port" class="dimension-checkbox"
                >端口风险</el-checkbox
              >
              <el-checkbox label="compliance" class="dimension-checkbox"
                >合规状态</el-checkbox
              >
              <el-checkbox label="threat" class="dimension-checkbox"
                >威胁情报</el-checkbox
              >
              <el-checkbox label="all" class="dimension-checkbox"
                >全部</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="生效时间">
            <el-radio-group v-model="ruleForm.effectTimeType">
              <el-radio label="permanent" class="time-radio">永久生效</el-radio>
              <el-radio label="custom" class="time-radio">指定时间段</el-radio>
            </el-radio-group>

            <el-row
              :gutter="10"
              v-if="ruleForm.effectTimeType === 'custom'"
              class="time-range"
            >
              <el-col :span="12">
                <el-date-picker
                  v-model="ruleForm.startTime"
                  type="date"
                  placeholder="开始日期"
                  style="width: 100%"
                />
              </el-col>
              <el-col :span="12">
                <el-date-picker
                  v-model="ruleForm.endTime"
                  type="date"
                  placeholder="结束日期"
                  style="width: 100%"
                />
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="规则说明">
            <el-input
              v-model="ruleForm.description"
              placeholder="请输入规则说明"
              maxlength="200"
            ></el-input>
          </el-form-item>

          <el-form-item label="是否启用">
            <el-switch
              v-model="ruleForm.status"
              active-value="enabled"
              inactive-value="disabled"
            ></el-switch>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button v-if="showRuleForm" type="default" @click="cancelRuleForm">
        取消
      </el-button>
      <el-button v-if="showRuleForm" type="primary" @click="saveRule">
        保存规则
      </el-button>
      <el-button
        v-if="!showRuleForm && selectedRules.length > 0"
        type="danger"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, onMounted, computed } from "vue";
import { ElMessage, ElForm, ElMessageBox } from "element-plus";
// import {
//   getWhitelistRules,
//   createWhitelistRule,
//   updateWhitelistRule,
//   deleteWhitelistRule,
// } from "@/api/falsePositive";

// 定义属性和事件
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue"]);

// 响应式数据
const visible = ref(props.modelValue);
const loading = ref(false);
const ruleList = ref([]);
const selectedRules = ref([]);
const showRuleForm = ref(false);
const isEditing = ref(false);
const currentRuleId = ref("");

// IP段配置
const ipRange = ref({
  startIp: "",
  endIp: "",
  cidr: "",
});

// 表单引用
const ruleFormRef = ref<InstanceType<typeof ElForm>>();

// 规则表单数据
const ruleForm = ref({
  name: "",
  type: "ip",
  range: "",
  dimensions: ["all"],
  effectTimeType: "permanent",
  startTime: "",
  endTime: "",
  description: "",
  status: "enabled",
});

// 监听显示状态变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (val) {
      fetchWhitelistRules();
    } else {
      resetForm();
    }
  }
);

// 获取白名单规则列表
const fetchWhitelistRules = async () => {
  loading.value = true;
  try {
    const { data } = await getWhitelistRules();
    ruleList.value = data.map((item, index) => ({
      ...item,
      serialNumber: index + 1,
    }));
  } catch (error) {
    ElMessage.error("获取白名单规则失败");
  } finally {
    loading.value = false;
  }
};

// 选择规则变化
const handleRuleSelectionChange = (rows) => {
  selectedRules.value = rows;
};

// 新增规则
const handleAddRule = () => {
  resetRuleForm();
  isEditing.value = false;
  currentRuleId.value = "";
  showRuleForm.value = true;
};

// 编辑规则
const handleEditRule = (row) => {
  resetRuleForm();
  isEditing.value = true;
  currentRuleId.value = row.id;

  // 填充表单数据
  ruleForm.value = {
    name: row.name,
    type: row.type,
    range: row.range,
    dimensions: row.dimensions || ["all"],
    effectTimeType: row.effectTimeType || "permanent",
    startTime: row.startTime ? new Date(row.startTime) : "",
    endTime: row.endTime ? new Date(row.endTime) : "",
    description: row.description || "",
    status: row.status || "enabled",
  };

  // 处理IP段数据
  if (row.type === "ip_range" && row.range) {
    if (row.range.includes("/")) {
      ipRange.value.cidr = row.range;
    } else if (row.range.includes("-")) {
      const [start, end] = row.range.split("-");
      ipRange.value.startIp = start.trim();
      ipRange.value.endIp = end.trim();
    }
  }

  showRuleForm.value = true;
};

// 保存规则
const saveRule = async () => {
  if (!ruleFormRef.value) return;

  try {
    // 处理IP段数据
    if (ruleForm.value.type === "ip_range") {
      if (ipRange.value.cidr) {
        ruleForm.value.range = ipRange.value.cidr;
      } else if (ipRange.value.startIp && ipRange.value.endIp) {
        ruleForm.value.range = `${ipRange.value.startIp} - ${ipRange.value.endIp}`;
      } else {
        ElMessage.warning("请输入IP段范围");
        return;
      }
    }

    await ruleFormRef.value.validate();

    loading.value = true;
    if (isEditing.value) {
      // 更新规则
      await updateWhitelistRule({
        id: currentRuleId.value,
        ...ruleForm.value,
      });
      ElMessage.success("规则更新成功");
    } else {
      // 创建规则
      await createWhitelistRule(ruleForm.value);
      ElMessage.success("规则创建成功");
    }

    showRuleForm.value = false;
    fetchWhitelistRules();
  } catch (error) {
    if (error.name !== "ValidationError") {
      ElMessage.error("操作失败，请重试");
    }
  } finally {
    loading.value = false;
  }
};

// 删除规则
const handleDeleteRule = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除规则"${row.name}"吗？`, "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await deleteWhitelistRule({ id: row.id });
    ElMessage.success("规则删除成功");
    fetchWhitelistRules();
  } catch (error) {
    // 取消删除不做处理
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRules.value.length === 0) return;

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的${selectedRules.value.length}条规则吗？`,
      "确认批量删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await deleteWhitelistRule({
      id: selectedRules.value.map((rule) => rule.id).join(","),
    });
    ElMessage.success(`已删除${selectedRules.value.length}条规则`);
    fetchWhitelistRules();
  } catch (error) {
    // 取消删除不做处理
  }
};

// 取消规则表单
const cancelRuleForm = () => {
  showRuleForm.value = false;
};

// 重置规则表单
const resetRuleForm = () => {
  ruleForm.value = {
    name: "",
    type: "ip",
    range: "",
    dimensions: ["all"],
    effectTimeType: "permanent",
    startTime: "",
    endTime: "",
    description: "",
    status: "enabled",
  };

  ipRange.value = {
    startIp: "",
    endIp: "",
    cidr: "",
  };

  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
};

// 重置表单
const resetForm = () => {
  ruleList.value = [];
  selectedRules.value = [];
  showRuleForm.value = false;
  isEditing.value = false;
  currentRuleId.value = "";
  resetRuleForm();
};

// 关闭对话框
const handleClose = () => {
  emit("update:modelValue", false);
};

// 辅助函数：获取规则类型名称
const getRuleTypeName = (type) => {
  const typeMap = {
    ip: "IP地址",
    ip_range: "IP段",
    port: "端口",
    cve: "CVE编号",
  };
  return typeMap[type] || type;
};
</script>

<style scoped lang="scss">
.whitelist-container {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.whitelist-card {
  margin-bottom: 15px;
  border-radius: 6px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: 500;
  color: #1d2129;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.no-rules {
  padding: 30px;
  text-align: center;
  color: #86909c;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-top: 10px;
}

.rule-form-card {
  border-top: 2px solid #1890ff;
}

.type-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 5px;
}

.type-radio {
  display: flex;
  align-items: center;
}

.or-text {
  margin: 5px 0;
  color: #86909c;
  font-size: 13px;
}

.dimension-checkbox {
  margin-right: 15px;
  margin-bottom: 10px;
}

.time-radio {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.time-range {
  margin-top: 10px;
}
</style>
